package com.ranchuanyin.schoolcat.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ranchuanyin.schoolcat.domain.AccountDetail;
import com.ranchuanyin.schoolcat.domain.CatAccount;
import com.ranchuanyin.schoolcat.dto.AccountDetailDTO;
import com.ranchuanyin.schoolcat.dto.AccountIdDTO;
import com.ranchuanyin.schoolcat.enums.SchoolCatExceptionEnum;
import com.ranchuanyin.schoolcat.exception.SchoolCatException;
import com.ranchuanyin.schoolcat.mapper.AccountDetailMapper;
import com.ranchuanyin.schoolcat.service.AccountDetailService;
import com.ranchuanyin.schoolcat.service.CatAccountService;
import com.ranchuanyin.schoolcat.vo.CatAccountDetailVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Objects;


/**
 * @author 33716
 * @description 针对表【account_detail】的数据库操作Service实现
 * @createDate 2023-11-07 16:40:50
 */
@Service
public class AccountDetailServiceImpl extends ServiceImpl<AccountDetailMapper, AccountDetail>
        implements AccountDetailService {
    @Resource
    CatAccountService catAccountService;

    @Override
    public CatAccountDetailVO getUserDetail(AccountIdDTO dto) {
        CatAccountDetailVO userDetail = this.baseMapper.getUserDetail(dto);
        if (Objects.isNull(userDetail)) {
            throw new SchoolCatException(SchoolCatExceptionEnum.NOT_DETAILED);
        }
        return userDetail;
    }

    @Override
    public Integer updateUserDetail(AccountDetailDTO dto) {
        LambdaQueryWrapper<AccountDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AccountDetail::getAccountId, dto.getAccountId());
        AccountDetail accountDetail = this.baseMapper.selectOne(wrapper);
        String userName = dto.getUserName();
        if (!userName.isEmpty()) {
            CatAccount catAccount = new CatAccount();
            catAccount.setId(dto.getAccountId());
            catAccount.setUsername(userName);
            catAccountService.updateById(catAccount);
        }

        AccountDetail bean = BeanUtil.toBean(dto, AccountDetail.class);

        if (Objects.isNull(accountDetail)) {
            return this.baseMapper.insert(bean);
        } else {
            LambdaUpdateWrapper<AccountDetail> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(AccountDetail::getAccountId, dto.getAccountId());
            return this.baseMapper.update(bean, updateWrapper);
        }
    }
}




